﻿using System;
using System.IO;
using System.Threading;
using Dexter.Search.Lucene.Storage;
using Lucene.Net.Store;
using Directory = Lucene.Net.Store.Directory;

namespace Dexter.Search.Lucene.Configuration.OnPremise {
	public class LuceneStorageService : ILuceneStorageService {
		readonly string baseLuceneFolder;
		
		/// <summary>
		/// Initializes a new instance of the <see cref="T:System.Object"/> class.
		/// </summary>
		public LuceneStorageService ( ) {
			baseLuceneFolder = Path.Combine ( AppDomain.CurrentDomain.BaseDirectory, "App_Data\\Lucene\\{0}\\" );
		}

		public Directory GetIndexDirectory (  ) {
			return GetIndexDirectory ( "default.catalog" );
		}

		public Directory GetIndexDirectory ( string catalog ) {
			string indexPath = string.Format(baseLuceneFolder, catalog);

			if (!System.IO.Directory.Exists ( indexPath ))
				System.IO.Directory.CreateDirectory ( indexPath );

			return FSDirectory.Open ( new DirectoryInfo ( indexPath ) );
		}

		internal string GetLuceneDirectoryPath ( string catalog ) {
			if(string.IsNullOrEmpty(catalog))
				catalog = "default.catalog";

			return string.Format ( baseLuceneFolder, catalog, Thread.CurrentThread.CurrentCulture );
		}
	}
}
